<template>
    <div class="place-page">
        <!-- 搜索 -->
        <div class="search-warp" @touchmove.stop.prevent="">
            <div class="input-warp">
                <div class="search">
                    <image src="@/static/icon-search.png"/>
                    <uni-easyinput
                        v-model="keyword"
                        class="uni-input" 
                        placeholder="搜索考点" 
                        :styles="inputStyle" 
                        placeholderStyle="color: #999;" 
                        :inputBorder="false" 
                        clearable
                        @clear="clearSearch"
                        @input="searchCenter"
                    >
                    </uni-easyinput>
                </div>
            </div>

            <!-- 搜索结果 -->
            <div v-show="searchList.length" class="search-result" @touchmove.stop.prevent="" @click="hideSearch">
                <scroll-view scroll-y="true" class="result-warp" @click.stop>
                    <hot-list :list="searchList" @selected="selectSchool"/>
                </scroll-view>
            </div>
        </div>
        <div v-show="!keyword || searchList.length">
            <!-- 选择了考点 -->
            <div class="selected" v-if="selectedName">
                <text class="title">已选考场：</text>
                <div class="city-name">
                    <span class="text">{{selectedName}}</span>
                    <div class="close-warp" @click="clearSelect">
                        <image class="clear" src="@/static/icon-close.png"/>
                    </div>
                </div>
            </div>

            <!-- 定位的城市 -->
            <div class="gps">
                <div class="close-gps" v-if="!currentCity">
                    <text class="title">所在城市</text>
                    <div class="text">获取定位失败，请检查网络或权限后<text class="again" @click="getGps">重试</text></div>
                </div>
                <div class="open-gps" v-if="currentCity">
                    <uni-icons class="icon-gps" type="location-filled" size="20" color="#FD453D"></uni-icons>
                    <text class="city">北京</text>
                    <uni-icons class="icon-again" type="loop" size="16" color="#CCCCCC" @click="getGps"></uni-icons>
                </div>
                <hot-list v-if="currentCity && schoolData.length" :list="schoolData" @selected="selectSchool"/>
            </div>

            <!-- 热门城市 -->
            <div class="hot-city" v-if="!currentCity">
                <div class="title">热门城市</div>
                <div class="city-list">
                    <div
                        class="city" 
                        :class="{active: hot === item.id}"
                        v-for="(item, index) in hotCities" 
                        :key="index"
                        @click="changeHot(item)"
                    >
                        {{item.name}}
                    </div>
                    
                </div>
                <hot-list v-if="schoolData.length" :list="schoolData" @selected="selectSchool"/>
            </div>

            <!-- 城市列表 -->
            <div class="tab-list">
                <div class="tab">
                    <div class="tab-item" :class="{active: currentTab === item.id}" v-for="(item) in tabs" :key="item.id" @click="changeTab(item.id)">
                        <view class="title">{{item.title}}</view>
                    </div>
                </div>
                <div v-if="currentTab === 1" class="china">
                    <city-list-tree :city-type="1" :list="cityTree" @selected="selectSchool"/>
                </div>
                <div v-else class="china not-china">
                    <city-list-tree :city-type="2" :list="cityTree" @selected="selectSchool"/>
                </div>
                <div class="py-list" v-if="currentTab == 1">
                    <text class="char" v-for="(item, index) in charList" :key="index">{{item}}</text>
                </div>
            </div>
        </div>
        <!-- 查询空态 -->
        <empty v-if="keyword && !searchList.length" text="未查询到您搜索的结果"/>
    </div>
</template>

<script>
    import HotList from '../components/hot-list.vue'
    import CityListTree from '../components/city-list-tree.vue'
    import { apiGetCityNameByXY, apiGetAllCityName, apiGetAllCentersByCity, apiSearchCenters } from '@/api/memory'
    import { Throttle } from '@/common/util/util'
    import Empty from '@/components/no-data.vue'
    export default {
        components: {
            HotList,
            CityListTree,
            Empty
        },
        options: {
            styleIsolation: 'shared'
        },
        data(){
            return {
                keyword: '', // 搜索关键字
                searchList: [], // 搜索结果
                tabs:[
                    {title: '国内 (含港澳台)', id: 1},
                    {title: '国外', id: 2},
                ],
                currentTab: 1,
                hotCities: [ // 热门城市列表
                    {name: '北京', id: 1},
                    {name: '上海', id: 2},
                    {name: '广州', id: 3},
                    {name: '深圳', id: 4},
                    {name: '成都', id: 5},
                ],
                hot:0, // 选中的热门城市
                schoolData: [], // 热门城市下的学校
                currentCity: '', // 定位城市
                cityTree: [],
                selectedName: '', // 选择的学校
                charList: [], // 首字母索引
                form: '' // 从哪个页面过来的
            }
        },
        created() {
            // this.getGps()
            this.getCityTree()
            const data = uni.getStorageSync('select-school') || {}
            this.selectedName = data.schoolName || data.cityName || ''
        },
        onLoad(option){
            this.from = option.from || ''
        },
        onShow(){
            this.getGps()
        },
        methods: {
            // 点击搜索蒙层关闭搜索弹窗
            hideSearch(){
                this.searchList = []
                this.keyword = ''
            },

            // 清除选择的学校
            clearSelect(){
                this.selectedName = ''
                try {
                    uni.setStorageSync('select-school', '')
                } catch (e) {
                    console.log(e, 'err')
                }
            },

            // 选择考点
            selectSchool(val){
                try {
                    uni.setStorageSync('select-school', {...val, from: this.from})
                    this.selectedName = val.schoolName || val.cityName || ''
                    uni.navigateBack()
                } catch (e) {
                    console.log(e, 'err')
                }
            },

            // 搜索 加节流
            searchSchool: Throttle(function(e){
                this.getHotCityData(e, true)
            }, 300),

            // 清除搜索
            clearSearch(){
                this.keyword = ''
                this.searchList = []
            },

            changeTab(tab){
                this.currentTab = tab
                this.getCityTree()
            },

            // 获取经纬度
            getGps(){
                const that = this
                uni.authorize({
                    scope: 'scope.userLocation',
                    success() {
                        uni.getLocation({
                            type: 'gcj02',
                            success (res) {
                                console.log('当前位置的经度：' + res.longitude)
                                console.log('当前位置的纬度：' + res.latitude)
                                that.getCityName(res.longitude, res.latitude)
                            },
                            fail(res){
                                console.log(res, '失败')
                                that.currentCity = ''
                                that.schoolData = []
                                uni.showModal({
                                    title: '提示',
                                    content: '获取位置信息失败，请检查网络或系统定位开关是否开启',
                                    showCancel: false,
                                    confirmText: '确定',
                                    success: res => {
                                    },
                                    fail: res => {
                                    }
                                });
                            }
                        });
                    },
                    fail(){
                        that.currentCity = ''
                        that.schoolData = []
                        console.log('定位授权失败')
                        uni.showModal({
                            title: '提示',
                            content: '尚未授权位置信息',
                            showCancel: true,
                            confirmText: '去授权',
                            success: res => {
                                if (res.confirm) {
                                    uni.openSetting({
                                        success(res) {
                                            console.log(res.authSetting)
                                        }
                                    })
                                }
                            }
                        });
                    }
                })
                
            },

            // 经纬度返回城市名
            getCityName(longitude, latitude){
                apiGetCityNameByXY({longitude, latitude}).then(res => {
                    if(res.code == 200){
                        this.currentCity = res.data
                        this.getHotCityData(res.data)
                    }
                }).catch(err => {
                    console.log(err, 'err')
                })
            },
            
            changeHot(city){
                this.hot = city.id
                this.getHotCityData(city.name)
            },

            // 城市的考点
            getHotCityData(cityName){
                apiGetAllCentersByCity({cityName}).then(res => {
                    if(res.code == 200){
                        this.schoolData = res.data || []
                    }
                }).catch(err => {
                    console.log(err, 'err')
                })
            },

            // 搜索
            searchCenter(centerName){
                apiSearchCenters({centerName}).then(res => {
                    if(res.code == 200){
                        this.searchList = res.data || []
                    }
                }).catch(err => {
                    console.log(err, 'err')
                })
            },
            
            // 获取所有城市
            getCityTree(){
                apiGetAllCityName({isChina: this.currentTab == 1}).then(res => {
                    if(res.code == 200){
                        this.cityTree = res.data.map(item => {
                            return {
                                ...item,
                                cityList: item.cityList.map(i => {
                                    return {
                                        ...i,
                                        showChildren: false,
                                        children: []
                                    }
                                })
                            }
                        })
                        this.charList = this.cityTree.map(item => item.firstChar) || []
                    }
                }).catch(err => {
                    console.log(err, 'err')
                })
            }
        },
    }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
    @function toRem($rpx){  //$rpx为需要转换的字号
        @return #{$rpx * 100 / 750 / 4}rem; 
    }
    .place-page{
        display: flex;
        flex-direction: column;
        height: 100%;
    }
    .input-warp{
        padding: toRem(30) toRem(30);
        box-sizing: border-box;
    }
    .search{
        box-sizing: border-box;
        // width: 100%;
        height: toRem(62);
        background-color: #F6F8FC;
        display: flex;
        align-items: center;
        color: #999;
        font-size: toRem(24);
        padding: toRem(17) toRem(32);
        border-radius: toRem(10);
        position: relative;
        z-index: 200;
        image{
            width: toRem(28);
            height: toRem(28);
            margin-right: toRem(23);
        }
        /deep/.uni-input{
            padding: 0;
            margin: 0;
            height: toRem(23);
            background-color: #F6F8FC;
            .uni-easyinput__content-input{
                height: toRem(23) !important;
                font-size: toRem(24) !important;
            }
            .uni-easyinput__content{
                min-height: auto !important;
                height: toRem(23) !important;
            }
        }
        /deep/.default-text{
            font-size: toRem(24);
            color: #999;
        }

    }
    .gps{
        width: 100%;
        padding: toRem(30);
        box-sizing: border-box;
        border-bottom: toRem(20) solid #F6F8FC;
        .close-gps{
            padding-bottom: toRem(30);
            .title{
                font-size: toRem(28);
                color: #333;
                font-weight: 500;
            }
            .text{
                font-size: toRem(24);
                color: #999;
                text-align: center;
                margin-top: toRem(29);
                .again{
                    color: #FD453D;
                }
            }
        }
        .open-gps{
            display: flex;
            align-items: center;
            color: #FD453D;
            font-size: toRem(28);
            .city{
                margin: 0 toRem(14) 0 toRem(9);
            }
        }
    }
    .selected{
        font-size: toRem(24);
        color: #333;
        display: flex;
        align-items: center;
        margin-left: toRem(30);
        .title{
            flex-shrink: 0;
        }
        .city-name{
            padding: toRem(12) toRem(19);
            background-color: #F6F8FC;
            font-weight: 500;
            position: relative;
            border-radius: toRem(8);
            flex-shrink: 1;
            margin-right: toRem(30);
            min-width: 0;
            .text{
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                display: inline-block;
                width: 100%;
            }
            .close-warp{
                padding: toRem(10);
                box-sizing: border-box;
                position: absolute;
                right: 0;
                top: 0;
                transform: translate(50%,-50%);
            }
            .clear{
                width: toRem(23);
                height: toRem(23);
            }
        }
    }
    .hot-city{
        padding: toRem(30);
        box-sizing: border-box;
        border-bottom: toRem(20) solid #F6F8FC;
        .title{
            color: #333;
            font-weight: 500;
            font-size: toRem(28);
            margin-bottom: toRem(22);
        }
        .city-list{
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            .city{
                flex: 1;
                height: toRem(68);
                background-color: #F6F8FC;
                border-radius: toRem(8);
                color: #333;
                font-size: toRem(24);
                font-weight: 500;
                text-align: center;
                margin: 0 toRem(10);
                display: inline-flex;
                align-items: center;
                justify-content: center;
                &.active{
                    background-color: rgba(253, 69, 61, .08);
                    color: #FD453D;
                }
                &:first-child{
                    margin-left: 0;
                }
                &:last-child{
                    margin-right: 0;
                }
            }
        }
    }
    .tab-list{
        padding-bottom: toRem(65);
        box-sizing: border-box;
        position: relative;
    }
    .tab{
        display: flex;
        align-items: center;
        justify-content: space-around;
        background-color: #fff;
        padding: toRem(30) 0 toRem(10);
        box-sizing: border-box;
        position: sticky;
        top:0;
        left:0;
        z-index: 100;
        box-shadow: 0 toRem(-2) #fff;
        padding-bottom: toRem(47);
        .tab-item{
            color: #999;
            font-size: toRem(28);
            padding-bottom: toRem(13);
            box-sizing: border-box;
            display: inline-flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            
        }
        .active{
            color: #666;
            font-weight: 500;
            &::after{
                content: '';
                display: inline-block;
                width: toRem(36);
                height: toRem(6);
                background-color: #FD453D;

            }
        }
    }
    .china{
        padding: 0 toRem(35);
        box-sizing: border-box;
    }
    .py-list{
        position: absolute;
        right: toRem(9);
        top: toRem(170);
        display: flex;
        flex-direction: column;
        align-items: center;
        z-index: 100;
        .char{
            color: #999;
            font-size: toRem(20);
            margin-bottom: toRem(10);
        }
    }
    .search-result{
        position: fixed;
        left: 0;
        bottom: 0;
        right: 0;
        top: toRem(79);
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,.7);
        z-index: 110;
        .result-warp{
            max-height: toRem(600);
            overflow: auto;
            background-color: #fff;
            padding: toRem(30);
            box-sizing: border-box;
        }
    }
    // .no-data{
    //     background-color: #fff;
    //     width: 100%;
    //     flex: 1;
    // }
</style>

